class UploadFile
  attr_reader :original_filename, :dir, :name, :extension, :tempfile
  def initialize(tempfile, options = {}) 
    raise "FileNotFound" unless tempfile
    @tempfile          = tempfile
    @original_filename = tempfile.original_filename
    @dir               = options[:namespace] || "upload_files"
    @name              = Digest::MD5.hexdigest(@original_filename +  Time.now.strftime("%Y%m%d%H%M%S")) + rand(1000000).to_s
    @extension         = original_filename.split(".").last
    @year              = Time.now.year
    @month             = Time.now.month
    @day               = Time.now.day
  end 

  def save
    @tempfile.close
    FileUtils.mkdir_p(file_dir)
    FileUtils.mv(@tempfile.path, generate_file_path)
    path = FileUtils.chmod(0644, generate_file_path).first
    {:url => url, :path => path}
  end 

  def url 
    "/#{@dir}/#{@year}/#{@month}/#{@day}/#{@name}.#{@extension}"
  end 

  def generate_file_path
    "#{RAILS_ROOT}/public/#{@dir}/#{@year}/#{@month}/#{@day}/#{@name}.#{@extension}"
  end 

  def file_dir
    "#{RAILS_ROOT}/public/#{@dir}/#{@year}/#{@month}/#{@day}/"
  end 
end
